/* eslint-disable no-eq-null */
/* eslint-disable @typescript-eslint/no-shadow */
import { $t } from '@/locales';
import type { DictDataOption } from '@/typings/global';

/**
 * Transform record to option
 *
 * @example
 *   ```ts
 *   const record = {
 *     key1: 'label1',
 *     key2: 'label2'
 *   };
 *   const options = transformRecordToOption(record);
 *   // [
 *   //   { value: 'key1', label: 'label1' },
 *   //   { value: 'key2', label: 'label2' }
 *   // ]
 *   ```;
 *
 * @param record
 */
export function transformRecordToOption<T extends Record<string, string>>(record: T) {
  return Object.entries(record).map(([value, label]) => ({
    value,
    label
  })) as CommonType.Option<keyof T>[];
}

/**
 * Translate options
 *
 * @param options
 */
export function translateOptions(options: CommonType.Option<string>[]) {
  return options.map(option => ({
    ...option,
    label: $t(option.label as App.I18n.I18nKey)
  }));
}

export function translateDictOptions(dicts: Array<DictDataOption>) {
  return dicts.map(dict => {
    return {
      label: dict.label,
      value: dict.value
    };
  });
  // return options.map(option => ({
  //   ...option,
  //   label: $t(option.label as App.I18n.I18nKey)
  // }));
}

/**
 * Toggle html class
 *
 * @param className
 */
export function toggleHtmlClass(className: string) {
  function add() {
    document.documentElement.classList.add(className);
  }

  function remove() {
    document.documentElement.classList.remove(className);
  }

  return {
    add,
    remove
  };
}
/**
 * 构造树型结构数据
 *
 * @param {any} data 数据源
 * @param {any} id id字段 默认 'id'
 * @param {any} parentId 父节点字段 默认 'parentId'
 * @param {any} children 孩子节点字段 默认 'children'
 */
export interface TreeNode {
  id: any;
  parentId: any;
  children?: TreeNode[];
  [key: string]: any; // 其他可能存在的字段
}

export const handleTree = <T extends TreeNode>(
  data: T[],
  idKey: string = 'id',
  parentKey: string = 'parentId',
  childrenKey: string = 'children'
): T[] => {
  const map: Record<any, T> = {};
  const tree: T[] = [];

  // 初始化 map
  data.forEach(item => {
    map[item[idKey]] = { ...item, [childrenKey]: [] };
  });

  // 构建树
  data.forEach(item => {
    const node = map[item[idKey]];
    const parentId = item[parentKey];
    if (parentId !== undefined) {
      const parent = map[parentId];
      if (parent) {
        parent[childrenKey].push(node);
      } else {
        // 如果父节点不存在，直接加入到树
        tree.push(node);
      }
    } else {
      // 如果没有父节点，作为根节点
      tree.push(node);
    }
  });

  // 清理空的 children 属性
  const cleanTree = (nodes: T[]): T[] => {
    return nodes.map(node => {
      const children = cleanTree(node[childrenKey]);
      if (children.length > 0) {
        return { ...node, [childrenKey]: children };
      }
      const { [childrenKey]: _, ...rest } = node;
      return rest as T;
    });
  };

  return cleanTree(tree);
};

// export const handleTree = <T>(data: any[], id?: string, parentId?: string, children?: string): T[] => {
//   const config: {
//     id: string;
//     parentId: string;
//     childrenList: string;
//   } = {
//     id: id || 'id',
//     parentId: parentId || 'parentId',
//     childrenList: children || 'children'
//   };

//   const childrenListMap: any = {};
//   const nodeIds: any = {};
//   const tree: T[] = [];

//   for (const d of data) {
//     const parentId = d[config.parentId];
//     if (childrenListMap[parentId] === null) {
//       childrenListMap[parentId] = [];
//     }
//     nodeIds[d[config.id]] = d;
//     childrenListMap[parentId].push(d);
//   }

//   for (const d of data) {
//     const parentId = d[config.parentId];
//     if (nodeIds[parentId] === null) {
//       tree.push(d);
//     }
//   }
//   const adaptToChildrenList = (o: any) => {
//     if (childrenListMap[o[config.id]] !== null) {
//       o[config.childrenList] = childrenListMap[o[config.id]];
//     }
//     if (o[config.childrenList]) {
//       for (const c of o[config.childrenList]) {
//         adaptToChildrenList(c);
//       }
//     }
//   };

//   for (const t of tree) {
//     adaptToChildrenList(t);
//   }

//   return tree;
// };

// 加载第三方库
export function loadjs(url: string, callback?: () => void): void {
  const script = document.createElement('script');
  const defaultCallback = () => {};
  const fun = callback || defaultCallback;
  script.type = 'text/javascript';
  script.onload = () => {
    // 回调
    fun();
  };
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}
// 验证是否为blob格式
export const blobValidate = (data: any) => {
  return data.type !== 'application/json';
};

// 生成 clientKey
export async function generateClientKey(length = 16) {
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  return Array.from(array)
    .map(byte => byte.toString(16).padStart(2, '0'))
    .join('');
}

// 生成 clientSecurity
export async function generateClientSecurity(length = 32) {
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  return Array.from(array)
    .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
    .join('');
}
export const removeEmptyProps = (obj: { [x: string]: any }) => {
  return Object.keys(obj).reduce((result, key) => {
    const value = obj[key];

    // 如果值是对象，递归调用处理
    if (value && typeof value === 'object' && !Array.isArray(value)) {
      const cleanedValue = removeEmptyProps(value);
      // 仅当递归处理后的对象非空时才添加到结果中
      if (Object.keys(cleanedValue).length > 0) {
        result[key] = cleanedValue;
      }
    } else if (value !== null && value !== undefined && value !== '') {
      result[key] = value;
    }

    return result;
  }, {});
};
